package com.xyy.controller;

import com.xyy.common.PageResult;
import com.xyy.common.Result;
import com.xyy.dto.*;
import com.xyy.entity.User;
import com.xyy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/user-manage")
@Validated
public class UserManageController {

    @Autowired
    private UserService userService;

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public Result<Void> updateUser(@Valid @RequestBody UserUpdateDTO updateDTO) {
        try {
            userService.updateUser(updateDTO);
            return Result.success();
        } catch (Exception e) {
            log.error("更新用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 软删除用户
     */
    @DeleteMapping("/delete/{userId}")
    public Result<Void> deleteUser(@PathVariable @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            userService.deleteUser(userId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量软删除用户
     */
    @DeleteMapping("/batch-delete")
    public Result<Void> batchDeleteUser(@RequestBody @NotEmpty(message = "用户ID列表不能为空") List<Long> userIds) {
        try {
            userService.batchDeleteUser(userIds);
            return Result.success();
        } catch (Exception e) {
            log.error("批量删除用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询用户
     */
    @PostMapping("/page")
    public Result<PageResult<User>> pageQueryUsers(@RequestBody(required = false) Map<String, Object> requestBody) {
        try {
            UserQueryDTO queryDTO = null;
            PageQueryDTO pageDTO = new PageQueryDTO();
            
            if (requestBody != null) {
                // 提取查询条件
                if (requestBody.containsKey("queryDTO")) {
                    Map<String, Object> queryMap = (Map<String, Object>) requestBody.get("queryDTO");
                    queryDTO = new UserQueryDTO();
                    
                    // 字符串类型参数
                    if (queryMap.containsKey("username")) queryDTO.setUsername((String) queryMap.get("username"));
                    if (queryMap.containsKey("nickname")) queryDTO.setNickname((String) queryMap.get("nickname"));
                    if (queryMap.containsKey("phone")) queryDTO.setPhone((String) queryMap.get("phone"));
                    if (queryMap.containsKey("email")) queryDTO.setEmail((String) queryMap.get("email"));
                    if (queryMap.containsKey("startTime")) queryDTO.setStartTime((String) queryMap.get("startTime"));
                    if (queryMap.containsKey("endTime")) queryDTO.setEndTime((String) queryMap.get("endTime"));
                    
                    // 整数类型参数 - 需要安全转换
                    if (queryMap.containsKey("gender")) {
                        Object genderObj = queryMap.get("gender");
                        if (genderObj instanceof String) {
                            try {
                                queryDTO.setGender(Integer.valueOf((String) genderObj));
                            } catch (NumberFormatException e) {
                                log.warn("性别参数格式错误，忽略此参数: {}", genderObj);
                            }
                        } else if (genderObj instanceof Integer) {
                            queryDTO.setGender((Integer) genderObj);
                        }
                    }
                    
                    if (queryMap.containsKey("status")) {
                        Object statusObj = queryMap.get("status");
                        if (statusObj instanceof String) {
                            try {
                                queryDTO.setStatus(Integer.valueOf((String) statusObj));
                            } catch (NumberFormatException e) {
                                log.warn("状态参数格式错误，忽略此参数: {}", statusObj);
                            }
                        } else if (statusObj instanceof Integer) {
                            queryDTO.setStatus((Integer) statusObj);
                        }
                    }
                }
                
                // 提取分页参数 - 也需要安全转换
                if (requestBody.containsKey("pageDTO")) {
                    Map<String, Object> pageMap = (Map<String, Object>) requestBody.get("pageDTO");
                    
                    if (pageMap.containsKey("current")) {
                        Object currentObj = pageMap.get("current");
                        if (currentObj instanceof String) {
                            try {
                                pageDTO.setCurrent(Integer.valueOf((String) currentObj));
                            } catch (NumberFormatException e) {
                                log.warn("当前页参数格式错误，使用默认值1: {}", currentObj);
                                pageDTO.setCurrent(1);
                            }
                        } else if (currentObj instanceof Integer) {
                            pageDTO.setCurrent((Integer) currentObj);
                        }
                    }
                    
                    if (pageMap.containsKey("size")) {
                        Object sizeObj = pageMap.get("size");
                        if (sizeObj instanceof String) {
                            try {
                                pageDTO.setSize(Integer.valueOf((String) sizeObj));
                            } catch (NumberFormatException e) {
                                log.warn("页大小参数格式错误，使用默认值10: {}", sizeObj);
                                pageDTO.setSize(10);
                            }
                        } else if (sizeObj instanceof Integer) {
                            pageDTO.setSize((Integer) sizeObj);
                        }
                    }
                }
            }
            
            if (queryDTO == null) {
                queryDTO = new UserQueryDTO();
            }
            
            // 设置默认值
            if (pageDTO.getCurrent() == null) pageDTO.setCurrent(1);
            if (pageDTO.getSize() == null) pageDTO.setSize(10);
            
            PageResult<User> result = userService.pageQueryUsers(queryDTO, pageDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询用户详情
     */
    @GetMapping("/detail/{userId}")
    public Result<User> getUserById(@PathVariable @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            User user = userService.getUserById(userId);
            return Result.success(user);
        } catch (Exception e) {
            log.error("查询用户详情失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 启用/禁用用户
     */
    @PutMapping("/toggle-status/{userId}")
    public Result<Void> toggleUserStatus(@PathVariable @NotNull(message = "用户ID不能为空") Long userId,
                                        @RequestParam @NotNull(message = "状态不能为空") Integer status) {
        try {
            userService.toggleUserStatus(userId, status);
            return Result.success();
        } catch (Exception e) {
            log.error("切换用户状态失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户列表（不分页）
     */
    @GetMapping("/list")
    public Result<List<User>> getUserList() {
        try {
            List<User> users = userService.list();
            return Result.success(users);
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询已删除的用户
     */
    @GetMapping("/deleted-users")
    public Result<PageResult<User>> getDeletedUsersPage(
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码必须大于0") Integer current,
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页大小必须大于0") Integer size) {
        try {
            PageResult<User> result = userService.getDeletedUsersPage(current, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询已删除用户失败", e);
            return Result.error("查询已删除用户失败: " + e.getMessage());
        }
    }



    /**
     * 恢复软删除的用户
     */
    @PutMapping("/restore/{userId}")
    public Result<Void> restoreUser(@PathVariable @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            userService.restoreUser(userId);
            return Result.success();
        } catch (Exception e) {
            log.error("恢复用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量恢复软删除的用户
     */
    @PutMapping("/batch-restore")
    public Result<Void> batchRestoreUsers(@RequestBody @NotNull(message = "用户ID列表不能为空") List<Long> userIds) {
        try {
            userService.batchRestoreUsers(userIds);
            return Result.success();
        } catch (Exception e) {
            log.error("批量恢复用户失败", e);
            return Result.error(e.getMessage());
        }
    }


} 